﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using EOSCRM.Domain;
using EOSCRM.Util;

namespace EOSCRM.Dao
{
    public class UserActionDao
    {
        readonly EventsLogDataContext _db;
        readonly string ConnectionString = "";
        public string SessionIdentify = "_EL_USER";
        private const string _dbName = "EventsLog";
        private const string _dbNameID = "Initial Catalog";
        public string Session4Log = "_INFO_4_LOG";

        public UserActionDao()
        {
            var connStr = ConfigurationManager.AppSettings[Constants.SETTINGS_CONNECTION];
            var decryptString = connStr; // EncryptUtil.Decrypt(connStr);

            var arrCS = decryptString.Split(';');

            for (var i = 0; i < arrCS.Length; i++)
            {
                var keyPair = arrCS[i].Split('=');
                if (keyPair.Count() == 2 && keyPair[0] == _dbNameID)
                    // EOSDN_EventsLog
                    arrCS[i] = string.Format("{0}={1}_{2}", keyPair[0], keyPair[1], _dbName);
            }
            ConnectionString = String.Join(";", arrCS);
        }

        public UserAction Get(int id) { return _db.UserActions.SingleOrDefault(w => w.Id == id); }

        public List<UserAction> GetList() { return _db.UserActions.OrderBy(o => o.LogId.ToString() + o.LogTime.ToString()).ToList(); }

        public void DuplicateType<anyType>(anyType Source, ref anyType Destination)
        {
            var curSession = HttpContext.Current.Session[Session4Log] as string[];
            if (curSession[1] == "") return;
            string[] Fields4Dup = curSession[1].Split(',');
            for (int i = 0; i < Fields4Dup.Length; i++)
                Destination.GetType().GetProperty(Fields4Dup[i]).SetValue(Destination,
                    Source.GetType().GetProperty(Fields4Dup[i]).GetValue(Source, null), null);
        }
    }
}
